layui.use(['layer', 'element', 'laytpl', 'jquery', 'table', 'upload', 'form'], function() {
	//引入模块
	var layer = layui.layer,
		element = layui.element,
		laytpl = layui.laytpl,
		form = layui.form,
		upload = layui.upload,
		table = layui.table,
		$ = layui.jquery;

	table.resize('testReload');

	if (localStorage.set != null) {
		//加载页面发生请求拿到数据
		$.ajax({
			url: "http://localhost:8080/sc/admin?type=home",
			async: true, //异步
			type: "POST",
			headers: {
				"token": localStorage.token
			},
			success: function(data) {
				//这里找id必须用js
				if (data.code == 'TokenFailed') {
					//删除token set
					delete localStorage.token;
					delete localStorage.set;
					layer.msg('登录失效，请重新登录！')
					setTimeout(function() {
						//调用父页面方法
						parent.tz();
					}, 1000);
				} else {
					var getTpl = document.getElementById('homemb').innerHTML,
						view = document.getElementById('homemoban');
					laytpl(getTpl).render(data, function(html) {
						view.innerHTML = html;
					});
				}
			}
		});

	} else {
		layer.msg('您还没有登录！')
		setTimeout(function() {
			parent.tz();
			//window.location.replace('admin_login.html');
		}, 1000);
	}

	//自动重载
	var token = localStorage.token;
	//表格重载
	table.reload('testReload', {
		url: 'http://localhost:8080/sc/admin?type=allp',
		headers: {
			token: token
		} //设定异步数据接口的额外参数
	});

	//定义上传图片次数
	var count = 0;
	//定义上传返回的图片地址
	var url1 = null,
		url2 = null,
		url3 = null,
		url4 = null,
		url5 = null,
		url6 = null,
		url7 = null;

	//载入加载分类给上架产品页面
	//动态添加下拉框 同时可以设置默认值
	$.ajax({
		url: 'http://localhost:8080/sc/admin2?type=queryc',
		dataType: 'json',
		type: 'post',
		headers: {
			"token": localStorage.token
		},
		success: function(data) {
			$.each(data, function(index, item) {
				console.log(item);
				//option 第一个参数是页面显示的值，第二个参数是传递到后台的值
				$('#selectId').append(new Option(item.name, item.id)); //往下拉菜单里添加元素
				$('#editck_select').append(new Option(item.name, item.id)); //往下拉菜单里添加元素
				//设置value（这个值就可以是在更新的时候后台传递到前台的值）为2的值为默认选中
			})
			form.render(); //更新全部表单内容
			//form.render('select'); //刷新表单select选择框渲染
		}
	});

	//监听行工具栏
	table.on('tool(tooltable)', function(obj) {
		var data = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
		if (layEvent == 'del') { //下架
			var id = data.id;
			layer.confirm('您确定要下架这个产品吗？', {
				btn: ['确定', '取消'] //按钮
			}, function() {
				//请求下架
				$.ajax({
					url: "http://localhost:8080/sc/admin?type=allpmsp&id=" + id,
					async: true, //异步
					type: "POST",
					headers: {
						"token": localStorage.token
					},
					success: function(data) {
						layer.msg('下架成功');
						obj.del();
					}
				});
			}, function() {});
		} else if (layEvent == 'detail') { //查看
			//请求图片
			$.ajax({
				url: "http://localhost:8080/sc/admin?type=ap&id=" + data.id,
				async: true, //异步
				type: "POST",
				headers: {
					"token": localStorage.token
				},
				success: function(dat) {
					$("#url2").attr("src", "http://localhost:8080/sc/images/" + dat.url2);
					$("#url3").attr("src", "http://localhost:8080/sc/images/" + dat.url3);
					$("#url4").attr("src", "http://localhost:8080/sc/images/" + dat.url4);
					$("#url5").attr("src", "http://localhost:8080/sc/images/" + dat.url5);
					$("#url6").attr("src", "http://localhost:8080/sc/images/" + dat.url6);
					$("#url7").attr("src", "http://localhost:8080/sc/images/" + dat.url7);
					//给窗口图片赋值
					$("#url1").attr("src", "http://localhost:8080/sc/images/" + data.url1);
					//给窗口赋值
					$("#pname").text(data.pname); //名字
					$("#spxq").text(data.detail); //详情
					$("#spjg").text(data.price); //价格
					$("#spxl").text(data.xl); //销量
					$("#spfl").text(dat.parentid); //分类
					//弹出窗口
					layer.open({
						type: 1,
						area: ['900px', '500px'],
						title: '查看产品信息',
						content: $("#chakanxx"),
						shade: 0,
						btn: ['确定'],
						btn1: function(index, layero) {
							layer.closeAll();
						},
						cancel: function(layero, index) {
							layer.closeAll();
						}
					});
				}
			});
		} else if (layEvent == 'edit') { //编辑
			//赋值id用户表单提交
			var id = data.id;
			//向后端请求规格，通过id
			$.ajax({
				url: "http://localhost:8080/sc/admin2?type=lqguige&id=" + id,
				async: true, //异步
				type: "POST",
				headers: {
					"token": localStorage.token
				},
				success: function(dat) {
					var gg = '';
					var kc = '';
					if (dat == '') {
						gg = '没有规格快来添加吧'
					}
					for (var i in dat) {
						gg = gg + dat[i].guige + '/';
						kc = kc + dat[i].kucun + '/'
					}
					//表单赋值
					form.val('editck_form', {
						"pname": data.pname,
						"detail": data.detail,
						"price": data.price,
						"gg": gg,
						"kc": kc,
						"parentid": data.parentid
					});
					//id赋值
					$('#editck_id').text(id)
				}
			});
			layer.open({
				type: 1,
				area: ['100%', '100%'],
				title: '编辑产品',
				content: $("#editck"),
				shade: 0,
				btn: ['确定'],
				btn1: function(index, layero) {
					$('#editck_xiugai').click();
				},
				cancel: function(layero, index) {
					//表单清空
					form.val('editck_form', {
						"pname": '',
						"detail": '',
						"price": '',
						"gg": '',
						"kc": '',
						"parentid": 0
					});
					//清空图片地址
					url1 = null;
					url2 = null;
					url3 = null;
					url4 = null;
					url5 = null;
					url6 = null;
					url7 = null;
					//重新定义点击次数
					count = 0;
					//删除图片元素
					$('#tpdz').remove();
					//重置进度条
					element.progress('editckprogressbar', '0%');

				}
			});
		}
	});

	//头工具栏事件
	table.on('toolbar(tooltable)', function(obj) {
		var checkStatus = table.checkStatus(obj.config.id); //获得表格选中的数据
		switch (obj.event) {
			case 'alldel': //批量下架
				if (checkStatus.data.length != 0) {
					layer.confirm('您确定要批量下架这些产品吗？', {
						btn: ['确定', '取消'] //按钮
					}, function() {
						//加载提示框
						var index = layer.load(1, {
							shade: [0.5, '#fff'] //0.1透明度的白色背景
						});
						var data = checkStatus.data;
						var id = '';
						for (let var1 in data) { //解析json多个对象
							id = id + '&id=' + (data[var1].id);
						}
						//请求下架
						$.ajax({
							url: "http://localhost:8080/sc/admin?type=allpmsp" + id,
							async: true, //异步
							type: "POST",
							headers: {
								"token": localStorage.token
							},
							success: function(data) {
								//关闭加载窗
								layer.close(index);
								layer.msg('成功下架', {
									time: 5000, //20s后自动关闭
									btn: ['知道了']
								});
								//表格重载
								table.reload('testReload', {
									url: 'http://localhost:8080/sc/admin?type=allp', //设定异步数据接口的额外参数
									headers: {
										token: token
									} //设定异步数据接口的额外参数
								});
							}
						})
					}, function() {
						layer.msg('成功取消', {
							time: 5000, //20s后自动关闭
							btn: ['知道了']
						});
					});
				} else {
					layer.msg('您还没选要下架的商品');
				}
				break;
			case 'upcp': //上架商品
				//弹出窗口
				layer.open({
					type: 1,
					area: ['100%', '100%'],
					title: '上架产品',
					content: $("#shangjia"),
					shade: 0,
					btn: ['提交产品'],
					btn1: function(index, layero) {
						if (url1 == null) {
							layer.msg('必须上传一张图片！')
						} else {
							$('#tijiaocp').click();
						}
					},
					cancel: function(layero, index) {
						layer.closeAll();
						//清空图片地址
						url1 = null;
						url2 = null;
						url3 = null;
						url4 = null;
						url5 = null;
						url6 = null;
						url7 = null;
						//重新定义点击次数
						count = 0;
						//删除图片元素
						$('#tpdz').remove();
						$('#cz').click();
					}
				});
				break;

		};
	});

	//搜索点击事件
	$('#ss').on('click', function() {
		//拿到输入框的值
		var keyword = $('#ssinput').val();
		var token = localStorage.token;
		//表格重载
		table.reload('testReload', {
			url: 'http://localhost:8080/sc/admin?type=ssp',
			where: {
				keyword: keyword
			},
			headers: {
				token: token
			} //设定异步数据接口的额外参数
		});
	});

	//控制上传图片数量
	$('#djsc').on('click', function() {
		count += 1;
		if (count <= 7) {
			$('#test2').click();
		} else {
			layer.msg('最多只能添加7张图片哦！亲');
		}
	});

	//编辑页面控制上传图片数量
	$('#editck_uploadimg').on('click', function() {
		count += 1;
		if (count <= 7) {
			$('#more_uploadimg').click();
		} else {
			layer.msg('最多只能添加7张图片哦！亲');
		}
	});

	$('#qktp').on('click', function() {
		//清空图片地址
		url1 = null;
		url2 = null;
		url3 = null;
		url4 = null;
		url5 = null;
		url6 = null;
		url7 = null;
		//重新定义点击次数
		count = 0;
		//删除图片元素
		$('#tpdz').remove();
		//重置进度条
		element.progress('jdt', '0%');
		layer.msg('清空完毕，你可以重新上传图片了', {
			icon: 1
		});
	});
	//编辑清空图片
	$('#editck_clearimg').on('click', function() {
		//清空图片地址
		url1 = null;
		url2 = null;
		url3 = null;
		url4 = null;
		url5 = null;
		url6 = null;
		url7 = null;
		//重新定义点击次数
		count = 0;
		//删除图片元素
		$('#tpdz').remove();
		//重置进度条
		element.progress('editckprogressbar', '0%');
		layer.msg('清空完毕，你可以重新上传图片了', {
			icon: 1
		});
	});

	//多图片上传
	upload.render({
		elem: '#test2',
		url: 'http://localhost:8080/sc/Upload' //改成您自己的上传接口
			,
		multiple: true,
		before: function(obj) {
			//预读本地文件示例，不支持ie8
			obj.preview(function(index, file, result) {
				$('#demo2').append('<img id = "tpdz" src="' + result +
					'" alt="' + file
					.name +
					'" class="layui-upload-img">')
			});
		},
		done: function(res) {
			switch (count) {
				case 1:
					url1 = res.data.src;
					break;
				case 2:
					url2 = res.data.src;
					break;
				case 3:
					url3 = res.data.src;
					break;
				case 4:
					url4 = res.data.src;
					break;
				case 5:
					url5 = res.data.src;
					break;
				case 6:
					url6 = res.data.src;
					break;
				case 7:
					url7 = res.data.src;
					break;
			}
		},
		progress: function(n, index, e) {
			element.progress('jdt', n + '%'); //可配合 layui 进度条元素使用
			if (n == 100) {
				layer.msg('上传完毕', {
					icon: 1
				});
			}
		}
	});

	//多图片上传//编辑页面的上传
	upload.render({
		elem: '#more_uploadimg',
		url: 'http://localhost:8080/sc/Upload' //改成您自己的上传接口
			,
		multiple: true,
		before: function(obj) {
			//预读本地文件示例，不支持ie8
			obj.preview(function(index, file, result) {
				$('#editck_lookimg').append('<img id = "tpdz" src="' + result +
					'" alt="' +
					file.name +
					'" class="layui-upload-img">')
			});
		},
		done: function(res) {
			switch (count) {
				case 1:
					url1 = res.data.src;
					break;
				case 2:
					url2 = res.data.src;
					break;
				case 3:
					url3 = res.data.src;
					break;
				case 4:
					url4 = res.data.src;
					break;
				case 5:
					url5 = res.data.src;
					break;
				case 6:
					url6 = res.data.src;
					break;
				case 7:
					url7 = res.data.src;
					break;
			}
			layer.msg(url1);
		},
		progress: function(n, index, e) {
			element.progress('editckprogressbar', n + '%'); //可配合 layui 进度条元素使用
			if (n == 100) {
				layer.msg('上传完毕', {
					icon: 1
				});
			}
		}

	});
	//编辑页面的上传

	//表单监听
	form.on('submit(tjcp)', function(data) {
		//layer.msg(JSON.stringify(data.field));
		// var a = JSON.stringify(data.field);
		// alert(a.pname)
		var loading = layer.load(1, {
			shade: [0.5, '#bcbcbc'] //0.1透明度的白色背景
		});
		var da = {
			detail: data.field.detail,
			pname: data.field.pname,
			parentid: data.field.parentid,
			price: data.field.price,
			gg: data.field.gg,
			kc: data.field.kc
		}
		$.ajax({
			// url: "http://localhost:8080/sc/admin2?type=addsp&pname=" + data.field
			// 	.pname +
			// 	"&detail=" + data.field.detail + "&parentid=" + data.field
			// 	.parentid +
			// 	"&price=" + data.field.price + "&gg=" + data.field.gg + "&kc=" +
			// 	data.field.kc +
			// 	"&url1=" + url1 + "&url2=" + url2 +
			// 	"&url3=" + url3 + "&url4=" + url4 + "&url5=" + url5 + "&url6=" +
			// 	url6 +
			// 	"&url7=" + url7,
			url: "http://localhost:8080/sc/admin2?type=addsp&url1=" + url1 + "&url2=" + url2 +
				"&url3=" + url3 + "&url4=" + url4 + "&url5=" + url5 + "&url6=" +
				url6 + "&url7=" + url7,
			dataType: "json",
			data: da,
			async: true, //异步
			type: "POST",
			headers: {
				"token": localStorage.token
			},
			success: function(data) {
				//清空图片地址
				url1 = null;
				url2 = null;
				url3 = null;
				url4 = null;
				url5 = null;
				url6 = null;
				url7 = null;
				//重新定义点击次数
				count = 0;
				//关闭加载窗口
				$('#cz').click();
				layer.close(loading);
				layer.msg(data.msg);
				setTimeout(function() { //延迟关闭
					layer.closeAll();
					location.reload();
				}, 1000);
			}
		})
		console.log(data.field.pname)
		return false; //一定要有这个玩意儿不然不会执行ajax
	});

	//表单监听编辑弹窗
	form.on('submit(editck_xiugai)', function(data) {
		// layer.msg(JSON.stringify(data.field));
		// var a = JSON.stringify(data.field);
		// alert(a.pname)
		//拿到产品id
		var id = $('#editck_id').text();
		var loading = layer.load(1, {
			shade: [0.5, '#bcbcbc'] //0.1透明度的白色背景
		});
		var da = {
			detail: data.field.detail,
			pname: data.field.pname,
			parentid: data.field.parentid,
			price: data.field.price,
			gg: data.field.gg,
			kc: data.field.kc,
			id: id
		}


		$.ajax({
			// url: "http://localhost:8080/sc/admin2?type=editP&pname=" + data.field
			// 	.pname +
			// 	"&detail=" + data.field.detail + "&parentid=" + data.field
			// 	.parentid +
			// 	"&price=" + data.field.price + "&gg=" + data.field.gg + "&kc=" +
			// 	data.field.kc +
			// 	"&url1=" + url1 + "&url2=" + url2 +
			// 	"&url3=" + url3 + "&url4=" + url4 + "&url5=" + url5 + "&url6=" +
			// 	url6 +
			// 	"&url7=" + url7+"&id="+id,
			url: "http://localhost:8080/sc/admin2?type=editP&url1=" + url1 + "&url2=" + url2 +
				"&url3=" + url3 + "&url4=" + url4 + "&url5=" + url5 + "&url6=" +
				url6 + "&url7=" + url7,
			dataType: "json",
			data: da,
			async: true, //异步
			type: "POST",
			headers: {
				"token": localStorage.token
			},
			success: function(data) {
				//清空图片地址
				url1 = null;
				url2 = null;
				url3 = null;
				url4 = null;
				url5 = null;
				url6 = null;
				url7 = null;
				//重新定义点击次数
				count = 0;
				//关闭加载窗口
				$('#cz').click();
				layer.close(loading);
				layer.msg(data.msg);
				setTimeout(function() { //延迟关闭
					layer.closeAll();
					location.reload();
				}, 1000);
			}
		})
		console.log(data.field.pname)
		return false; //一定要有这个玩意儿不然不会执行ajax
	});
});
